package edu.ege.thesis.nyt;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/*

 TimesArticleSearchResult Class
 
 February, 2009
 blprnt@blprnt.com

*/


public class TimesArticleSearchResult {


String cmonth;
  String cyear;

  String[] facetStrings;
  int total;

  JSONObject facets;
  TimesResultObject[] results;

  TimesArticleSearchResult() {
  };

  void processResults(JSONArray e, String f) {
    System.out.println("PROCESS");
    results = new TimesResultObject[e.length()];
    for (int i=0; i < e.length(); i++) {
      String[] fields = f.split(",");
      TimesResultObject r = new TimesResultObject();
      JSONObject o;
      try {
        o = e.getJSONObject(i);
        
        for (int j = 0; j < fields.length; j++) {
          
          String s = fields[j];
          
          if (s.matches("body")) {
            //println("SET BODY");
            r.setBody(o.getString("body"));
          }
          else if (s.matches("title")) {
            //println("SET TITLE");
            //println(":" + o.getString("title"));
            r.setTitle(o.getString("title"));
          }
          else if (s.matches("abstract")) {
            r.set_abstract(o.getString("abstract"));
          }
          else if (s.matches("url")) {
            r.setUrl(o.getString("url"));
          }
          else if (s.matches("author")) {
            r.setAuthor(o.getString("author"));
          }
          else if (s.matches("date")) {
            r.setDate(o.getString("date"));
          }
          else if (s.matches("byline")) {
            r.setByline(o.getString("byline"));
          };
        };

      }
      catch (JSONException je) {

      };
      
      results[i] = r;
    };
  };
  /*
  
   getFacetList
   - Returns an array of TimesFacetObjects
   
   */

  TimesFacetObject[] getFacetList(String facetName) {

    int facetNum = 0;
    TimesFacetObject[] flist;

    try {
      JSONArray facetArray = (JSONArray) facets.getJSONArray(facetName);
      facetNum = facetArray.length();
      flist = new TimesFacetObject[facetNum];

      for (int i = 0; i < facetNum; i++) {
        //1. Retrieve the JSONObject
        JSONObject jo;
        try {
          jo = (JSONObject) facetArray.get(i);
        }
        catch (JSONException e)  {
          jo = new JSONObject();
        };

        //2 For each item, create a TFO
        TimesFacetObject tfo = new TimesFacetObject();
        tfo.count = jo.getInt("count");
        tfo.term = jo.getString("term");

        //3 File it into the array
        flist[i] = tfo;
      };

    }
    catch (JSONException e) {
      flist = new TimesFacetObject[facetNum];
    };

    return(flist);
  };


  public TimesResultObject[] getResults() {
		return results;
	}

};






